<?php

namespace app\model;

use think\Model;

class SyncRecord extends Model
{
    protected $table = 'sync_records';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 类型转换
    protected $type = [
        'total_synced' => 'integer',
        'total_skipped' => 'integer',
        'duplicate_count' => 'integer',
        'error_count' => 'integer',
        'duration_seconds' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
        'started_at' => 'datetime',
        'completed_at' => 'datetime'
    ];

    /**
     * 创建同步记录
     */
    public static function createRecord($syncType, $startDate, $endDate)
    {
        $record = new self();
        $record->sync_type = $syncType;
        $record->start_date = $startDate;
        $record->end_date = $endDate;
        $record->sync_status = 'running';
        $record->started_at = date('Y-m-d H:i:s');
        $record->save();
        
        return $record;
    }

    /**
     * 更新同步记录
     */
    public function updateProgress($totalSynced, $totalSkipped, $duplicateCount, $errorCount, $errorMessages = [])
    {
        $this->total_synced = $totalSynced;
        $this->total_skipped = $totalSkipped;
        $this->duplicate_count = $duplicateCount;
        $this->error_count = $errorCount;
        $this->error_messages = !empty($errorMessages) ? json_encode($errorMessages, JSON_UNESCAPED_UNICODE) : null;
        $this->save();
    }

    /**
     * 完成同步记录
     */
    public function complete($status = 'completed')
    {
        $this->sync_status = $status;
        $this->completed_at = date('Y-m-d H:i:s');
        $this->duration_seconds = time() - strtotime($this->started_at);
        $this->save();
    }

    /**
     * 获取同步记录列表
     */
    public static function getRecordList($page = 1, $limit = 20, $filters = [])
    {
        $query = self::order('started_at', 'desc');
        
        // 应用过滤器
        if (!empty($filters['sync_type'])) {
            $query->where('sync_type', $filters['sync_type']);
        }
        
        if (!empty($filters['sync_status'])) {
            $query->where('sync_status', $filters['sync_status']);
        }
        
        if (!empty($filters['start_date'])) {
            $query->where('start_date', '>=', $filters['start_date']);
        }
        
        if (!empty($filters['end_date'])) {
            $query->where('end_date', '<=', $filters['end_date']);
        }
        
        return $query->paginate([
            'list_rows' => $limit,
            'page' => $page
        ]);
    }

    /**
     * 获取同步统计信息
     */
    public static function getSyncStats()
    {
        $stats = [
            'total_records' => self::count(),
            'running_records' => self::where('sync_status', 'running')->count(),
            'completed_records' => self::where('sync_status', 'completed')->count(),
            'failed_records' => self::where('sync_status', 'failed')->count(),
            'total_synced' => self::sum('total_synced'),
            'total_errors' => self::sum('error_count')
        ];
        
        return $stats;
    }

    /**
     * 获取最近的同步记录
     */
    public static function getRecentRecords($limit = 10)
    {
        return self::order('started_at', 'desc')->limit($limit)->select();
    }

    /**
     * 获取正在运行的同步任务
     */
    public static function getRunningTasks()
    {
        return self::where('sync_status', 'running')->select();
    }
} 